package com.wsyu.springbootbackend.core.auth.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsyu.springbootbackend.core.util.HttpServletUtils;
import com.wsyu.springbootbackend.core.util.JsonUtils;
import lombok.Setter;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

class LoginToken extends HashMap<String, String> {
    public String getUsername() {
        return super.getOrDefault(CustomUsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "");
    }

    public String getPassword() {
        return super.getOrDefault(CustomUsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "");
    }
}

@Setter
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    public CustomUsernamePasswordAuthenticationFilter() {
        super();
    }

    public CustomUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if (!HttpServletUtils.isJsonContentType(request) || !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("仅支持：POST application/json 登录认证");
        } else {
            // 如果需要自定义参数名，可以在这里修改
            // 例如从JSON获取：
            // 使用Jackson解析请求体
            String jsonStr = HttpServletUtils.getJsonBody(request);
            System.out.println(jsonStr);
            LoginToken loginMap = JsonUtils.parseObject(jsonStr, LoginToken.class);
            String username = loginMap.getUsername().trim();
            String password = loginMap.getPassword().trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);

        }
    }

}
